package com.lms.common.file.utils;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.SocketException;

@Slf4j
public class FtpFileUtil extends AbstractFileUtil {

    @Resource
    private ConnectParams connectParams;

    @Override
    public void init() {

    }

    private FTPClient getClient() {
        FTPClient client = new FTPClient();
        try {
            client.connect(connectParams.getIp(), connectParams.getPort());
            client.login(connectParams.getUsername(), connectParams.getPassword());
            client.setControlEncoding(connectParams.getEncode());
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 被动模式
            client.enterLocalPassiveMode();
            if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
                log.error("未连接到FTP");
            } else {
                log.info("连接ftp成功");
            }
        } catch (SocketException e) {
            log.error("连接下载文件的FTP失败", e);
        } catch (IOException e) {
            log.error("连接ftp异常", e);
        }
        return client;
    }

    @Override
    public boolean upload(InputStream fileInputStream, String targetPath, String fileName) {
        FTPClient client = this.getClient();
        try {
            // 切换到工作目录
            if (!client.changeWorkingDirectory(targetPath)) {
                client.changeWorkingDirectory("/");
                String[] dirs = targetPath.split("/");
                for (String dir : dirs) {
                    client.makeDirectory(dir);
                    client.changeWorkingDirectory(dir);
                }
            }
            // 工作模式被动
            client.enterLocalPassiveMode();
            // 文件写入 远程文件名；输入流
            boolean storeFile = client.storeFile(fileName, fileInputStream);
            if (!storeFile) {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(client);
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                log.error("关闭IO流异常！", e);
            }
        }
        return true;
    }

    @Override
    public InputStream download(String path, String fileName) {
        FTPClient client = this.getClient();
        try {
            client.changeWorkingDirectory(path);
            ByteArrayOutputStream fos = new ByteArrayOutputStream();
            fos.flush();
            client.retrieveFile(fileName, fos);
            return new ByteArrayInputStream(fos.toByteArray());
        } catch (IOException e) {
            log.error("操作ftp客户端异常！", e);
        } finally {
            close(client);
        }
        return null;
    }

    @Override
    public boolean delete(String path, String fileName) {
        FTPClient client = this.getClient();
        try {
            client.deleteFile(path + "/" + fileName);
        } catch (IOException e) {
            log.error("操作ftp客户端异常！", e);
            return false;
        } finally {
            close(client);
        }
        return true;
    }

    public void close(FTPClient client) {
        try {
            if (client != null && client.isConnected()) {
                client.abort();
                client.disconnect();
            }
        } catch (IOException e) {
            log.error("ftp客户端关闭异常！", e);
        }
    }

}
